package com.tuling.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;

import java.util.List;

/**
 * @author :tangweiliang
 * @date : 2023/6/3 9:51
 * 未来的你会感谢现在努力的自己
 */
// 访问redis单机
public class JedisSingleTest {
    public static void main(String[] args) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMinIdle(5);

        // timeout，这里既是连接超时又是读写超时，从Jedis 2.8开始有区分connectionTimeout和soTimeout的构造函数
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "192.168.126.129", 6379, 3000, null);

        Jedis jedis = null;
        try {
            //从redis连接池里拿出一个连接执行命令
            jedis = jedisPool.getResource();
//            System.out.println(jedis.set("single", "123"));
//            System.out.println(jedis.get("single"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //注意这里不是关闭连接，在JedisPool模式下，Jedis会被归还给资源池。
            if (jedis != null) {
                jedis.close();
            }
        }

        //管道示例
        //管道的命令执行方式：cat redis.txt | redis‐cli ‐h 127.0.0.1 ‐a password ‐ p 6379 ‐‐pi
        Pipeline pipelined = jedis.pipelined();
        for (int i = 0; i < 10; i++) {
            pipelined.incr("pipeline");
            pipelined.set("twl" + 1, "twl");
            //模拟管道报错
            pipelined.setbit("twl", -1, true);
        }
        List<Object> result = pipelined.syncAndReturnAll();
        System.out.println(result);
    }
}
